package org.yourscrum.persistence;

import org.yourscrum.domain.Theme;
import org.yourscrum.domain.ThemeRepository;
import org.springframework.stereotype.Repository;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.List;

/**
 * @author Jettro Coenradie
 */
@Repository("themeRepository")
public class JdoThemeRepository extends JdoRepository implements ThemeRepository {

    public Theme createTheme(Theme theme) {
        return storeEntity(theme);
    }

    public Theme updateTheme(Theme theme) {

        PersistenceManager pm = getPmFactory().getPersistenceManager();
        try {
            pm.makePersistent(theme);
            return pm.detachCopy(theme);
        } finally {
            pm.close();
        }
    }

    public Theme obtainThemeById(long id) {
        PersistenceManager pm = getPmFactory().getPersistenceManager();
        try {
            Theme theme = pm.getObjectById(Theme.class, id);
            return pm.detachCopy(theme);
        } finally {
            pm.close();
        }
    }

    public List<Theme> obtainAllThemes() {
        PersistenceManager pm = getPmFactory().getPersistenceManager();
        try {
            Query query = pm.newQuery(Theme.class);
            List<Theme> result = (List<Theme>) query.execute();
            return (List<Theme>) pm.detachCopyAll(result);
        } finally {
            pm.close();
        }
    }
}
